Examples of Subroutines With Labeled Parameters
This section provides examples of subroutine definitions with labeled parameters and of calls to those subroutines.The following subroutine converts inches to centimeters:
on CentimeterConversion from x --make sure the parameter is a real number or an integer if class of x is contained by {integer, real} return x * 2.54 else error "The parameter must be a real number or an integer" end if end CentimeterConversion --to call CentimeterConversion: CentimeterConversion of 36The following subroutine searches for a specific string in a list of files.
to searchFiles of filesToSearch for theString --filesToSearch: list of Scriptable Text Editor files --theString: the string to be searched for set hits to {} tell application "Scriptable Text Editor" repeat with i from 1 to (count items of filesToSearch) set currentFile to item i of filesToSearch if contents of document currentFile contains theString --append currentFile to list of hits set hits to hits & currentFile end if end repeat return hits end tell end searchFiles --to call searchFiles: searchFiles of {"March Expenses", "April Expenses", ÿ "May Expenses", "June Expenses"} for "LeChateau"The specified files must be open for the searchFiles handler to work.The following subroutine uses the special label
given
to define a parameter with the labelrounding
. By using verb forms ending with "ing" as labels, you can often make subroutine calls easier to read.
to findNumbers of numberList above minLimit ÿ given rounding:roundBoolean set resultList to {} repeat with i from 1 to (count items of numberList) set x to item i of numberList if roundBoolean = true then copy (x + 0.5) div 1 to x end if if x > minLimit then copy resultList & x to resultList end if end repeat return resultList end findNumbers --to call findNumbers: findNumbers of myList above 3 given rounding:trueAnother way to call thefindNumbers
subroutine is to use a With or Without clause to specify the value of therounding
parameter. You can use With or Without clauses to specify parameters whose values aretrue
orfalse
.
--this call is equivalent to the previous example findNumbers of myList above 3 with roundingThe subroutine parameter labels that can be used without the special labelgiven
allow you considerable flexibility in defining handlers that sound English-like. For example, here's a routine that takes any parameter that
can be displayed as a string and displays it in a dialog box:
on rock around the clock display dialog (clock as string) end rockThe statement
rock around the current datelater in the same script displays the current date in a dialog box.Here's another example of the use of subroutine parameter labels:
to check for yourNumber from bottom thru top if bottom ≤ yourNumber and yourNumber ≤ top then display dialog "Congratulations! You scored." end if end checkThe statement
check for 8 from 7 thru 10later in the same script displays the specified dialog box.